//
//  WorkQualityController.swift
//  vmes
//
//  Created by 志鹏 翟 on 2021/12/2.
//

import UIKit
import Alamofire

class WorkQualityController: BaseController, UIPickerViewDataSource, UIPickerViewDelegate {
    
    let pickerView=UIPickerView()
    
    let top=UIView()
    let planNum=UILabel()
    let alreadyNum=UILabel()
    let waitNum=UILabel()
    
    let area=UIView()
    let planNumLb=UILabel()
    let allNumLb=UILabel()
    let waitNumLb=UILabel()
    
    //创建textField
    let textField_buliang = UITextField()
    let textField_remark = UITextField()
    let textField_type = UITextField()
    
    let scrollview=UIScrollView()
    
    var orderInfo:OrderItem?
    
    var data:[Dict]?
    var currentDict:Dict?
    
    let toolbar = UIToolbar()
    
    override func viewDidLayoutSubviews() {
        scrollview.frame.size=view.frame.size
        scrollview.frame.size.height-=view.safeAreaInsets.top
        scrollview.frame.origin.y=view.safeAreaInsets.top
        scrollview.contentSize = CGSize(width: view.frame.width, height: 800)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.getDict()
        navigationController?.navigationBar.tintColor = .black
        self.navigationItem.title="工单开工"
        self.view.backgroundColor = .white
        top.backgroundColor=UIColor.colorWithHex(hexStr: "#E3E5E7")
        top.layer.cornerRadius=10
        //        view.addSubview(top)
        view.addSubview(scrollview)
        // 可以滚动的区域
        scrollview.addSubview(top)
        top.snp.makeConstraints { make in
            make.top.equalTo(view.safeAreaInsets.top)
            make.left.equalTo(view.snp.left).offset(15)
            make.right.equalTo(view.snp.right).offset(-15)
            make.height.equalTo(284)
        }
        let orderNoLb=UILabel()
        orderNoLb.text="orderNo"
        let desc1Lb=UILabel()
        let desc2Lb=UILabel()
        let statusLb=UILabel()
        statusLb.text="生产中"
        let planStartLb=UILabel()
        planStartLb.text="计划开始"
        let realStartLb=UILabel()
        realStartLb.text="实际开始"
        let planStopLb=UILabel()
        planStopLb.text="计划结束"
        let realStopLb=UILabel()
        realStopLb.text="实际结束"
        let planStart=UILabel()
        planStart.font = .systemFont(ofSize: 14)
        let planStop=UILabel()
        planStop.font = .systemFont(ofSize: 14)
        let realStart=UILabel()
        realStart.font = .systemFont(ofSize: 14)
        let realStop=UILabel()
        realStop.font = .systemFont(ofSize: 14)
        [orderNoLb,statusLb,desc1Lb,desc2Lb,planStop,planStart,
         planStopLb,planStartLb,realStop,realStart,realStopLb,realStartLb].forEach {
            top.addSubview($0)
        }
        orderNoLb.snp.makeConstraints { make in
            make.top.left.equalToSuperview().offset(20)
        }
        desc1Lb.snp.makeConstraints { make in
            make.left.equalTo(orderNoLb.snp.left)
            make.top.equalTo(orderNoLb.snp.bottom).offset(10)
        }
        desc2Lb.snp.makeConstraints { make in
            make.left.equalTo(orderNoLb.snp.left)
            make.top.equalTo(desc1Lb.snp.bottom)
        }
        statusLb.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-15)
            make.top.equalTo(orderNoLb.snp.top)
        }
        let line=UIView()
        line.backgroundColor = UIColor.colorWithHex(hexStr: "#6F6F6F")
        top.addSubview(line)
        line.snp.makeConstraints { make in
            make.height.equalTo(0.5)
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.centerX.equalTo(top.snp.centerX)
            make.top.equalTo(desc2Lb.snp.bottom)
                .offset(15)
        }
        //计划
        planStartLb.snp.makeConstraints { make in
            make.top.equalTo(line.snp.bottom).offset(15)
            make.left.equalTo(orderNoLb.snp.left)
        }
        planStart.snp.makeConstraints { make in
            make.top.equalTo(planStartLb.snp.bottom).offset(10)
            make.left.equalTo(planStartLb.snp.left)
        }
        planStopLb.snp.makeConstraints { make in
            make.top.equalTo(planStart.snp.bottom).offset(40)
            make.left.equalTo(planStartLb.snp.left)
        }
        planStop.snp.makeConstraints { make in
            make.top.equalTo(planStopLb.snp.bottom).offset(10)
            make.left.equalTo(planStopLb.snp.left)
        }
        //实际
        realStartLb.snp.makeConstraints { make in
            make.top.equalTo(line.snp.bottom).offset(15)
            make.left.equalTo(top.snp.centerX).offset(10)
        }
        realStart.snp.makeConstraints { make in
            make.top.equalTo(realStartLb.snp.bottom).offset(10)
            make.left.equalTo(realStartLb.snp.left)
        }
        realStopLb.snp.makeConstraints { make in
            make.top.equalTo(realStart.snp.bottom).offset(40)
            make.left.equalTo(realStartLb.snp.left)
        }
        realStop.snp.makeConstraints { make in
            make.top.equalTo(realStopLb.snp.bottom).offset(10)
            make.left.equalTo(realStartLb.snp.left)
        }
        //绑定数据
        orderNoLb.text=orderInfo?.workorderCode
        desc1Lb.text=orderInfo?.productCode ?? "暂无产品内容"
        desc2Lb.text=orderInfo?.productName ?? "暂无产品内容"
        if("0"==orderInfo?.statusFlag!){
            statusLb.text="待生产"
        }else if("1"==orderInfo?.statusFlag!){
            statusLb.text="当班开工"
        }else if("2"==orderInfo?.statusFlag!){
            statusLb.text="当班完工"
        }else if("3"==orderInfo?.statusFlag!){
            statusLb.text="已完成"
        }
        planStart.text=orderInfo?.planStartTime
        planStop.text=orderInfo?.planEndTime
        realStart.text=orderInfo?.actualStartTime
        realStop.text=orderInfo?.actualEndTime
        
        initNumLabel()
        initInputArea()
        
        // 设置数据源和代理
        pickerView.dataSource = self
        pickerView.delegate = self
    }
    
    func initNumLabel(){
        let planNumLb=UILabel()
        let allNumLb=UILabel()
        let waitNumLb=UILabel()
        planNumLb.text="总排产量"
        allNumLb.text="已报工量"
        waitNumLb.text="当班计划量"
        
        [planNumLb,allNumLb,waitNumLb].forEach({
            scrollview.addSubview($0)
            $0.textAlignment = .center
            $0.textColor=UIColor.colorWithHex(hexStr: "#333333")
            $0.font = UIFont.systemFont(ofSize: 15)
        })
        planNumLb.snp.makeConstraints { make in
            make.width.equalTo(width/3)
            make.top.equalTo(top.snp.bottom).offset(20)
        }
        allNumLb.snp.makeConstraints { make in
            make.width.equalTo(width/3)
            make.top.equalTo(top.snp.bottom).offset(20)
            make.left.equalTo(planNumLb.snp.right)
        }
        waitNumLb.snp.makeConstraints { make in
            make.width.equalTo(width/3)
            make.top.equalTo(top.snp.bottom).offset(20)
            make.left.equalTo(allNumLb.snp.right)
        }
        [planNum,alreadyNum,waitNum].forEach({
            scrollview.addSubview($0)
            $0.textAlignment = .center
            $0.text="500"
            $0.textColor=UIColor.colorWithHex(hexStr: "#0FA386")
            $0.font = UIFont.systemFont(ofSize: 20)
        })
        planNum.snp.makeConstraints { make in
            make.centerX.equalTo(planNumLb.snp.centerX)
            make.top.equalTo(planNumLb.snp.bottom).offset(5)
        }
        alreadyNum.snp.makeConstraints { make in
            make.centerX.equalTo(allNumLb.snp.centerX)
            make.top.equalTo(planNumLb.snp.bottom).offset(5)
        }
        waitNum.snp.makeConstraints { make in
            make.centerX.equalTo(waitNumLb.snp.centerX)
            make.top.equalTo(planNumLb.snp.bottom).offset(5)
        }
        planNum.text=String(orderInfo?.scheduleNumber ?? 0)
        alreadyNum.text=String(orderInfo?.workreportOutput ?? 0)
        waitNum.text=String(orderInfo?.shiftPlanOutput ?? 0)
    }
    
    func initInputArea(){
        let area=UIView()
        area.backgroundColor = UIColor.colorWithHex(hexStr: "#0FA386")
        scrollview.addSubview(area)
        area.snp.makeConstraints { make in
            make.top.equalTo(planNum.snp.bottom).offset(40)
            make.left.equalTo(view.snp.left).offset(15)
            make.right.equalTo(view.snp.right).offset(-15)
            make.height.equalTo(360)
        }
        let inner=UIView()
        inner.layer.cornerRadius=10
        inner.backgroundColor = .white
        area.addSubview(inner)
        inner.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
            make.top.equalToSuperview().offset(30)
            make.bottom.equalToSuperview().offset(-30)
        }
        
        inner.addSubview(textField_type)
        textField_type.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(40)
            make.top.equalToSuperview().offset(20)
        }
        
        [textField_buliang,textField_remark].forEach({
            inner.addSubview($0)
            $0.textAlignment = .right
            $0.text="0"
            $0.keyboardType = .decimalPad
            $0.textColor=UIColor.colorWithHex(hexStr: "#0FA386")
            $0.font = UIFont.systemFont(ofSize: 20)
            $0.leftViewMode = .always
        })
        textField_type.inputView=pickerView
        let labelLx=UILabel()
        labelLx.text="类型"
        textField_type.leftView = labelLx
        textField_type.textAlignment = .right
        textField_type.leftViewMode = .always
        textField_type.font = UIFont.systemFont(ofSize: 20)
        let doneButton = UIBarButtonItem(title: "完成", style: .done, target: self, action: #selector(doneButtonClicked))
        toolbar.items = [doneButton]
        toolbar.sizeToFit()
        
        // 将 toolbar 添加到 textField 的 inputAccessoryView 上
        textField_type.inputAccessoryView = toolbar
        
        textField_remark.keyboardType = .default
        textField_remark.text=""
        let label=UILabel()
        label.text="确认不良品数"
        textField_buliang.leftView = label
        
        let label2=UILabel()
        label2.text="备注"
        textField_remark.leftView = label2
        textField_buliang.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(40)
            make.top.equalTo(textField_type.snp.bottom).offset(20)
        }
        let line=UIView()
        line.backgroundColor = UIColor.colorWithHex(hexStr: "#6F6F6F")
        inner.addSubview(line)
        line.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(1)
            make.top.equalTo(textField_buliang.snp.bottom)
        }
        textField_remark.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(40)
            make.top.equalTo(line.snp.bottom).offset(20)
        }
        let line2=UIView()
        line2.backgroundColor = UIColor.colorWithHex(hexStr: "#6F6F6F")
        inner.addSubview(line2)
        line2.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(1)
            make.top.equalTo(textField_remark.snp.bottom)
        }
        let btn=UIButton()
        btn.layer.cornerRadius=5
        inner.addSubview(btn)
        btn.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.top.equalTo(line2).offset(30)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(55)
        }
        btn.setTitle("提交质检信息", for: .normal)
        btn.backgroundColor = UIColor.colorWithHex(hexStr: "#FD8D19")
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 20)
        btn.setTitleColor(UIColor.colorWithHex(hexStr: "#ffffff"), for: .normal)
        btn.addTarget(self, action: #selector(showConfrimAlert), for: .touchUpInside)
    }
    
    @objc func doneButtonClicked() {
        // 这里处理 Done 按钮点击后的逻辑
        // 比如获取 UIPickerView 的选中值，关闭键盘等
        let selectedRow = pickerView.selectedRow(inComponent: 0)
        currentDict=data?[selectedRow]
        let selectedValue = data?[selectedRow].dictLabel // 假设你有一个名为dataArray的数组存储选项值
        
        // 隐藏键盘
        textField_type.resignFirstResponder()
        textField_type.text = selectedValue
        
        // 处理 selectedValue 或其他逻辑
        // ...
    }
    
    @objc func showConfrimAlert(){
        let alertView = UIAlertController.init(title: "提示", message: "确认质检么", preferredStyle: .alert)
        let alert = UIAlertAction.init(title: "确定", style: .destructive) { (UIAlertAction) in
            self.finishWork()
        }
        let cancleAlert = UIAlertAction.init(title: "取消", style: .cancel) { (UIAlertAction) in
            print("点击取消按钮")
        }
        alertView.addAction(cancleAlert)
        alertView.addAction(alert);
        self.present(alertView, animated: true, completion: nil)
    }
    
    private func getDict(){
        spinner.startAnimating()
        AF.request(NetInfo.getDict, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: K.headers!).responseJSON { response in
            self.spinner.stopAnimating()
            print(response)
            switch response.result {
            case .success:
                if let data=response.data{
                    let response = try? JSONDecoder().decode(DictList.self, from: data)
                    if(response?.code==200){
                        self.data=response?.data
                    }else{
                        self.view.makeToast(response?.msg)
                    }
                }
            case .failure:
                print("ERROR")
                self.view.makeToast("请求失败")
            
            }
        }
    }
    
    
    @objc func finishWork(){
        spinner.startAnimating()
        let parameters: Dictionary = [
            "compId" : K.userInfo?.company?.companyId!,
            "qcUser" : K.userInfo?.userId!,
            "workorderCode" : orderInfo?.workorderCode!,
            "workshopId" : K.currentWorkShop?.workshopId!,
            "scheduleId":orderInfo?.id!,
            "qcRejectNumber" : textField_buliang.text,
            "remarkInfo" : textField_remark.text,
            "dictValue" : currentDict?.dictValue
        ]
        AF.request(NetInfo.qualityWork, method:.put
                   , parameters:parameters,encoder: JSONParameterEncoder.default,headers: K.headers!,
                   requestModifier: { $0.timeoutInterval = 10 }).responseJSON { (response) in
            self.spinner.stopAnimating()
            print(response)
            switch response.result {
            case .success:
                if let data=response.data{
                    let response = try? JSONDecoder().decode(LoginInfo.self, from: data)
                    if(response?.code==200){
                        self.view.makeToast("质检成功",duration:2)
                        self.perform(#selector(self.backItemPressed), with: nil, afterDelay: 2)
                    }else{
                        self.view.makeToast(response?.msg)
                    }
                }
            case .failure:
                print("ERROR")
                self.view.makeToast("请求失败")
            }
        }
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return data?.count ?? 0
    }
    
    // 返回组件数量
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    // 返回每个组件的行数
    func numberOfRows(inComponent component: Int) -> Int {
        return data?.count ?? 0
    }
    
    // 返回每行的标题
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return data?[row].dictLabel
    }
    
    // 处理用户选择
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
//        print("1112222")
//        textField_type.text = data[row]
//        // 隐藏 pickerView（如果需要的话）
//        textField_type.resignFirstResponder()
    }
    
    
}

